/**
*    Copyright (C) 2008  Chase Kernan 
*    chase.kernan@gmail.com
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
**/


package com.chasekernan.hxnova.utils;

import hscript.Parser;
import hscript.Interp;

/**
    This class loads variable definitions and uses a bit of reflection to 
    change the static variables defined in classes dynamically.
    
    The loaded data is in the form of an hscript file.
**/
class VarLoader {
    
    //thanks to filt3rek for the basis for this -- 
    //http://filt3r.free.fr/index.php/2008/07/23/59-hscript
    
    /**
        Loads the variables from the given data (in the form of an hscript 
        script).
    **/
    public static function load(data : String) {
        var parser = new Parser();
        var program = parser.parseString(data);
        var interp = new Interp();
        interp.variables.set("class", getClass);
        interp.execute(program);
    }

    private static function getClass(s : String) {
        return Type.resolveClass(s);
    }   
}

#if unit

class VarLoaderTest extends haxe.unit.TestCase {
    
    var script : String;
    
    private static var TEST_VARIABLE_INT = 5;
    private static var TEST_VARIABLE_STRING = "test";
    
    public function new(){
		super();		
	}
    
    override public function setup() {
        script = 
        "
        var test = 'testing';
        var varLoader = class('com.chasekernan.hxnova.utils.VarLoaderTest');
        varLoader.TEST_VARIABLE_STRING = test.toUpperCase();
        varLoader.TEST_VARIABLE_INT = 23 * test.length;
        ";
    }
    
	public function testLoad() {
        VarLoader.load(script);
        
		assertEquals("testing".length * 23, TEST_VARIABLE_INT);
        assertEquals("TESTING", TEST_VARIABLE_STRING);
	}
}
#end

